<template>
  <div class="bluetooth">
    <!-- 蓝牙状态 -->
    <div class="bluetooth-status">
      <div class="text">蓝牙状态： </div>
      <div class="desc">{{msg}}</div>
    </div>
    
  </div>
</template>

<script>

export default {
  data () {
    return {
      msg: 'init',
      bluetoothStatus: false, // 蓝牙状态
    }
  },
  onLoad () {
    this.startConnect()
  },
  onShow () {

  },
  methods: {
    // 1. 初始化蓝牙
    startConnect () {
      var that = this;
      // 提示
      wx.showLoading({
        title: '开启蓝牙适配' //提示的内容,
      });

      // 1.1 开启蓝牙适配器
      wx.openBluetoothAdapter({
        success: res => {
          console.log('初始化蓝牙设备：', res)
          wx.showToast({
            title: '蓝牙已开启', //提示的内容,
            icon: 'none', //图标,
            duration: 4000, //延迟时间,
          });
          // that.getBluetoothAdapterState();
        },
        fail: res => {
          wx.showToast({
            title: '初始化蓝牙失败', //提示的内容,
            icon: 'none', //图标,
            duration: 4000, //延迟时间,
          });
        },
        complete: res => {
          // wx.hideLoading();
        }
      });

      // 2. 开启蓝牙状态监听, 判断是否可用
      wx.onBluetoothAdapterStateChange(res => {
        var available = res.available;
        if (available) {
          // that.getBluetoothAdapterState();
        }
      });
    },

    // 3. 开始搜索蓝牙设备
    startBluetoothDevicesDiscovery () {
      var that = this;
      // 提示
      wx.showLoading({
        title: '蓝牙搜索中...', //提示的内容,
      });
      // 3. 开启蓝牙搜索
      wx.startBluetoothDevicesDiscovery({
        services: [], // 要搜索的蓝牙设备主 service 的 uuid 列表
        allowDuplicatesKey: false, // 是否允许上报同一设备
        success: res => {
          console.log('开始搜索蓝牙设备: ', res)
          if (!res.isDiscovering) {
            // 获取适配器状态
            // that.getBluetoothAdapterState();
          } else {
            // 搜索蓝牙设备
            // that.onBluetoothDeviceFound();
          }
        },
        fail: err => {
          console.log(err)
        }
      });
    },

    // 4. 连接蓝牙设备
    getConnectedBluetoothDevices () {
      var that = this;
      // 连接
      wx.getConnectedBluetoothDevices({
        services: [that.servicesId], //蓝牙设备主 service 的 uuid 列表,
        success: res => {
          console.log('获取处于连接状态的设备', res)
          var devices = res['devices'], flag = false, index = 0, conDevList = [];
          // 遍历
          devices.forEach(function (value, index, array) {
            console.log(value, index)
          });
        }
      });
    },

  }
}
</script>

<style lang="scss" scoped>
.bluetooth {
  padding: 20rpx;
}
// status
.bluetooth-status {
  display: flex;
  font-size: 28rpx;
  .desc {
    flex: 1;
  }
}

</style>
